// pages2/pages/index/urgentContact/index.js
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import * as Storage from '../../../../utils/storage'
const $api = require("../../../../request/api").API
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		equipId: "",
		equipType: 1,
		list: ["", "", ""],
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad({
		equipId,
		equipType
	}) {
		let list = this.data.list
		if (equipType == 2) {
			list = ['']
		}
		this.setData({
			equipId,
			equipType,
			list
		})
		this.getData()
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {

	},
	async getData() {
		let res = await $api.getSafeEquipContact({
			equipId: this.data.equipId
		})
		res = res.data.data

		if (res && res.fastPhones) {
			let fastPhones = res.fastPhones.split(",")
			if (fastPhones.length < 3) {
				let numToAdd = 3 - fastPhones.length;
				fastPhones = fastPhones.concat(Array(numToAdd).fill(''));
			}
			this.setData({
				list: fastPhones
			})
		}
	},
	onDelete(e) {
		const prop = `list[${e.currentTarget.dataset.prop}]`
		this.setData({
			[prop]: ""
		})
	},
	// 输入
	onInput({
		currentTarget,
		detail
	}) {
		let prop = `list[${currentTarget.dataset.prop}]`
		this.setData({
			[prop]: detail.value
		})
	},
	checkData() {
		const {
			list
		} = this.data
		const phoneReg = /^\d+$/
		if (!list.filter(Boolean).length) {
			Toast.fail("至少填写一个联系电话")
			return
		}
		for (let index in list) {
			if (list[index] && !phoneReg.test(list[index])) {
				Toast.fail(`第${(Number(index)+1)}个电话号码格式错误`)
				return
			}

		}
		return true
	},
	submit() {
		if (!this.checkData()) return
		Dialog.confirm({
			title: "提示",
			message: "确定保存"
		}).then(() => {
			Toast.loading({
        message: '请等待...',
        duration: 0
      });
			const {
				list,
				equipId
			} = this.data

			const params = {
				equipId,
				fastPhones: list.filter(Boolean).toString()
			}
			$api.setSafeEquipContact(params).then(res => {
				if(res.data.status==0){
					Toast.success("设置成功")
				}else{
					Toast.fail(res.data.msg)
				}
			}).catch(err=>{
				Toast.fail(err.msg)
			})
		}).catch(() => {

		})
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})